package cn.healthlink.proxy.demo04;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

/**
 * @author dengzhiyuan
 * @version 1.0
 * @time 2021/1/20 14:47
 */
public class JdkDynamicProxy implements InvocationHandler {

	private Object target;

	/**
	 * 拦截器列表
	 */
	private List<MyMethodInterceptor> interceptorList = new ArrayList<>();

	public void addInterceptorList(MyMethodInterceptor interceptor) {
		this.interceptorList.add(interceptor);
	}

	public JdkDynamicProxy(Object target) {
		this.target = target;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		TargetParam targetParam = new TargetParam();
		targetParam.setMethod(method);
		targetParam.setTarget(target);
		targetParam.setArgs(args);
		MyMethodInvocation methodInvocation = new MyMethodInvocationImpl(targetParam,interceptorList);

		return methodInvocation.proceed();
	}

	public Object getProxy(){
		return Proxy.newProxyInstance(target.getClass().getClassLoader()
				,target.getClass().getInterfaces(),this);
	}

}
